package com.ayitubie.refuelweb.controller;

import com.alibaba.excel.EasyExcel;
import com.ayitubie.refuelweb.config.annotation.OptLog;
import com.ayitubie.refuelweb.config.interceptor.loginUserInterceptor.UserContext;
import com.ayitubie.refuelweb.config.jedis.JedisService;
import com.ayitubie.refuelweb.entity.LogEsVo;
import com.ayitubie.refuelweb.entity.RefuelLog;
import com.ayitubie.refuelweb.entity.RefuelLogForExcel;
import com.ayitubie.refuelweb.minio.MinioTemplate;
import com.ayitubie.refuelweb.service.FileServ;
import com.ayitubie.refuelweb.service.RefuelLogServ;
import com.ayitubie.refuelweb.validation.group.Groups;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@Configuration
@RefreshScope
@RequestMapping("/refuel")
public class RefuelLogCtl {
    @Autowired
    private RefuelLogServ refuelLogServ;

    @Autowired
    private FileServ fileServ;

    @Autowired
    JedisService jedisService;

    @Autowired
    RedissonClient redissonClient;

    @Value("${sftp.path}")
    private String path;

    @GetMapping("query/getPerMonth")
    @OptLog(optType = "统计")
    public List<RefuelLog> getPerMonth() throws Exception {
        return refuelLogServ.getPerMonth();
    }

    @GetMapping("query/all")
    public PageInfo<RefuelLog> getAllRefuelLogByUserId(HttpServletRequest request,
                                                       HttpServletResponse response,
                                                       @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                                       @RequestParam(required = false, defaultValue = "0") Integer pageSize,
                                                       @RequestParam(required = false, defaultValue = "0") float payMoney,
                                                       @RequestParam(required = false, defaultValue = "0") float payMoneyLow,
                                                       @RequestParam(required = false, defaultValue = "") String stationIds
    ) throws Exception {
        List result = new ArrayList<T>();
        if (StringUtils.isNotEmpty(stationIds)){
            result = Arrays.asList(stationIds.split(","));
        }
        return refuelLogServ.getRefuelLogByUserId(pageNum, pageSize, payMoney,payMoneyLow,result);
    }

    @PostMapping("query/es/all")
    public List<SearchHit<RefuelLog>> elasticsearchLog(@RequestBody LogEsVo vo) {

        return refuelLogServ.elasticsearchLog(vo);
    }

    @GetMapping("excel")
    public void getAllRefuelLogAllByUserId(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("加油记录", "UTF-8");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), RefuelLogForExcel.class).sheet("加油记录").doWrite(refuelLogServ.getRefuelLogsAll());
    }

    @GetMapping("processExcel")
    public void processExcel(HttpServletResponse response) throws IOException, InterruptedException {
        refuelLogServ.processExcel();
    }


    @PostMapping("/create")
    public Long refuelCreate(@RequestBody @Validated(Groups.Add.class) RefuelLog refuelLog, HttpServletRequest request) throws Exception {
        refuelLog.setUserId(UserContext.getUser().getUserId());
        log.info("新增 [{}]", refuelLog);
        return refuelLogServ.refuelCreate(refuelLog, request);
    }

    @DeleteMapping("/delete/{refuel_id}")
    public int deleteRefuelById(@PathVariable Long refuel_id) {
        return refuelLogServ.delRefuelById(refuel_id);
    }

    @PostMapping("/updateInfo/{refuel_id}")
    public Long updateRefuelById(@RequestBody @Validated({Groups.Update.class}) RefuelLog refuelLog, @PathVariable Long refuel_id) {
        refuelLog.setRefuel_id(refuel_id);
        return refuelLogServ.updateRefuelById(refuelLog);
    }

    @PostMapping("/photo")
    public String onloadPhoto(@RequestParam(value = "file", required = true) MultipartFile file) {
        String fileName = "";
        try {
            fileName = fileServ.upload(file, path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    @GetMapping("/query/oilPrice")
    public String getOilPrice() {
        return refuelLogServ.getOilPrice(false);
    }

    @GetMapping("/getAvgOil")
    public float getAvgOil() {
        return refuelLogServ.getAvgOil();
    }

    @GetMapping("/query/weather")
    public String getWeather() {
        return refuelLogServ.getWeather(false);
    }

    @GetMapping("/antiWeightToken")
    public String getAntiWeight() throws Exception {
        String key = "";
        RSemaphore semaphore = redissonClient.getSemaphore("TimeLimit");
        int count = semaphore.availablePermits();
        if (count == 0) {
            throw new Exception("次数用光了，您已被限流！");
        }
        boolean flag = semaphore.tryAcquire();
        if (flag) {
            key = UUID.randomUUID().toString().replace("-", "");
            jedisService.setEx(key, "", 1800);
        } else {
            throw new Exception("次数用光了，您已被限流！");
        }

        return key;
    }
}
